<template>
  <div>
    <div class="page-body">
      <div class="page-left" v-loading="loadingLeft">
        <data-view v-model="cmpList" v-model:searchValue="cmpSearchv" :header-btn="['search']"
          :current-page="cmpCurrentPage" :page-size="pageSize" :total="cmpDataTotal" @search="onCmpSearch"
          @update:current-page="onUpdateCmpCurrentPage">
          <template #content="{ dataItem }">
            <cmp-card class="page-left-item" :class="{
              'page-left-item-select': selectCmp?.Id == dataItem.Id
            }" style="flex-grow: 1;margin:5px;" :card-data="dataItem" @click="onClickCmp(dataItem)"></cmp-card>
          </template>
        </data-view>
      </div>
      <div class="page-right" v-loading="rightLoading">
        <div class="page-right-none" v-if="!selectCmp">
          点击左侧公司,查询对应视频
        </div>
        <template v-else>
          <div class="page-right-none" v-if="dyList.length == 0">
            当前公司暂无绑定抖音号
          </div>
          <template v-else>
            <el-tabs v-model="selectDyId" class="demo-tabs" @tab-click="onTabClick">
              <el-tab-pane v-for="item in dyList" :label="item.AwemeName" :name="item.AwemeShortId"></el-tab-pane>
            </el-tabs>
            <div class="page-right-con">

              <div class="page-right-con-item" v-for="item in dataList">
                <img :src="item.cover" alt="" srcset="">
                <div class="page-right-con-itemcon">
                  <div style="flex-shrink: 0;">{{ item.title || "无标题" }}</div>
                  <div style="flex-shrink: 0; padding-top:5px;color:rgba(0,0,0,0.5)"> {{ item._create_time }}</div>
                  <div style="flex-grow: 1;padding:10px 0">
                    <template v-if="dyVideoStateMap.get(item.video_id)">
                      <!-- //表示正常挂载小程序了 -->
                      <div v-if="dyVideoStateMap.get(item.video_id)?.ErrNo == 0"
                        style="font-size: 15px;color:rgba(0,0,0,0.5)">
                        <el-tag>已挂载卡券</el-tag>
                        {{ dyVideoStateMap.get(item.video_id)?.Title }}
                      </div>
                      <!-- 出问题的 -->
                      <div style="color:red" v-else>
                        <el-tag type="danger">错误</el-tag>
                        {{ dyVideoStateMap.get(item.video_id)?.ErrMsg }}
                      </div>
                    </template>
                  </div>
                  <div class="page-right-con-itemcon-footer">
                    <a :href="item.share_url" title="查看原视频" target="_blank">查看原视频</a>
                    <el-button v-if="!dyVideoStateMap.get(item.video_id)" style="margin-left: 10px;"
                      @click="openModalView(item)">
                      挂载卡券
                    </el-button>
                  </div>
                </div>
              </div>
              <!-- 加载错误, 或者为空 -->
              <div class="page-right-none" v-if="dataList.length == 0">
                {{ errorText }}
              </div>
              <!-- 下一页 -->
              <div v-else class="page-right-page">
                <el-button v-if="dataList.length == dyLimit * dyPage" @click="onClickNextPage()">加载下一页</el-button>
                <div v-else>
                  加载完成
                </div>
              </div>
            </div>
          </template>

        </template>
      </div>
    </div>
    <modal-view ref="modalViewRef" v-if="isModalViewRefShow" @close="isModalViewRefShow = false" @submit="onEcardSubmit">
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "ECardRule",
})
</script>

<script lang="ts" setup>
import { ref, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DataView from "@/components/DataView";
import { docType, DyVideoDataClass } from "@/model/DyVideo";
import { queryGet } from "@/utils/api";
import { request } from "@/utils/axios";
import { appState } from "@/store/app"
import { getPanelUxBtn, getMenuAction } from "@/utils/bus";
import CmpCard from "@/views/pages/Cmp/CmpCard.vue";
import { CmpDataClass } from "@/model/Cmp";
import ModalView from "./DyVideoECardRuleModalView.vue"

let menuActionType = ref(getMenuAction("ECardRule"))
let menuActionArray = ref(getPanelUxBtn("ECardRule"));


/**
 * 每页数据数量
 */
let pageSize = ref(25);

/**
 * ====================
 *  左侧数据
 * ====================
 */

/**
 * 选择的公司id
 */
let selectCmp = ref<CmpDataClass | null>(null);

/**
 * 左侧loading
 */
let loadingLeft = ref(false);

/**
 * 公司列表
 */
let cmpList = ref<CmpDataClass[]>([]);

/**
 * 公司查询
 */
let cmpSearchv = ref("");

/**
 * 页数
 */
let cmpCurrentPage = ref(1);

/**
 * 公司总数量
 */
let cmpDataTotal = ref(0);

/**
 * 当点击搜索的时候 
 */
function onCmpSearch() {
  cmpCurrentPage.value = 1;
  selectCmp.value = null;
  getCmpList();
}

/**
 * 当前变更页数的时候
 */
function onUpdateCmpCurrentPage(count: number) {
  cmpCurrentPage.value = count;
  selectCmp.value = null;
  //重新加载数据
  getCmpList();
}

/**
 * 获取公司数据
 */
function getCmpList() {
  loadingLeft.value = true;
  queryGet({
    docType: "Cmp",
    actionType: "PageList",
    apiType: "PageList",
    limit: pageSize.value
  }, {
    Searchv: cmpSearchv.value,
    Start: cmpCurrentPage.value,
  })
    .then((res) => {
      cmpList.value = res.List.map((item: any) => {
        return new CmpDataClass(item);
      })
      cmpDataTotal.value = res.Total;
    })
    .finally(() => {
      loadingLeft.value = false;
    })
}

/**
 * 单击某家公司
 */
function onClickCmp(row: CmpDataClass) {
  selectCmp.value = row;
  //获取公司抖音
  getDouYin()
}

/**
 * ====================
 *  主数据
 * ====================
 */

let rightLoading = ref(false);

/**
* -----------
*  抖音号数据
* -----------
*/

let selectDyId = ref("")

/**
 * 抖音列表
 */
let dyList = ref<{
  OpenId: string;
  AwemeShortId: string;
  AwemeName: string
}[]>([])

/**
 * 获取抖音数据
 */
function getDouYin() {
  rightLoading.value = true;
  dyList.value = [];
  selectDyId.value = "";
  queryGet({
    docType: "Cmp",
    actionType: "DyMicroAweme",
    apiType: "SingleList"
  }, {
    Id: selectCmp.value?.Id
  })
    .then((res) => {
      dyList.value = res.map((item: any) => {
        return {
          OpenId: item.OpenId,
          AwemeShortId: item.AwemeShortId,
          AwemeName: item.AwemeName
        }
      })
      if (dyList.value.length > 0) {
        selectDyId.value = dyList.value[0].AwemeShortId;
        nextTick(() => {
          onTabClick({
            paneName: selectDyId.value
          });
        })
      } else {
        rightLoading.value = false;
      }
    })
    .catch(() => {
      rightLoading.value = false;
    })
}


/**
 * 页签变更
 */
function onTabClick(para: any) {
  nextTick(() => {
    maxCursor.value = "0";
    dataList.value = [];
    dyPage.value = 0;
    getData();
  })
}

/**
 * -----------
 *  视频
 * -----------
 */

let dataList = ref<DyVideoDataClass[]>([]);

/**
 * 当前第几页
 */
let dyPage = ref<number>(0);

/**
 * 每页 数量
 */
let dyLimit = 30;

/**
 * 游标
 */
let maxCursor = ref<string>("0");

/**
 * 错误提示
 */
let errorText = ref("");

/**
 * 获取数据
 */
function getData() {
  let dy = dyList.value.find(item => item.AwemeShortId == selectDyId.value);
  if (!dy) return;
  if (!dy.OpenId) {
    errorText.value = "暂未授权,请抖音号持有者在小程序中登录";
    // ElMessageBox.alert(errorText.value, "操作提示");
    rightLoading.value = false;
    return;
  }
  rightLoading.value = true;
  request("/DyVideo/GetVideoListByAweme", {
    "OpenId": dy.OpenId,//人员openid
    "AwemeShortId": dy.AwemeShortId,//人员的抖音号
    "Start": maxCursor.value,//分页游标（第一页传入0，后续可传入返回值中的max_cursor来查询下一页）。字符串类型
    "Limit": dyLimit//每页条数。不能超过100
  })
    .then((res) => {
      if (res && res.max_cursor) {
        maxCursor.value = res.max_cursor;
        dyPage.value++;
        let list: DyVideoDataClass[] = res.list.map((item: any) => {
          return new DyVideoDataClass(item);
        });
        dataList.value = dataList.value.concat(list);
        getDyVideoState(list.map(item => item.video_id));
      } else {
        errorText.value = "暂无可用短视频";
      }
    })
    .finally(() => {
      rightLoading.value = false;
    })
}

/**
 * 加载下一页
 */
function onClickNextPage() {
  getData();
}

/**
 * 抖音视频状态
 */
let dyVideoStateMap = ref<Map<string, {
  ErrNo: number;
  ErrMsg: string;
  Title: string
}>>(new Map())

/**
 * 获取视频状态
 */
function getDyVideoState(Ids: string[]) {
  queryGet({
    docType: "DyVideo",
    actionType: "MountMicro",
    apiType: "SingleList"
  }, {
    Ids: Ids
  })
    .then((res) => {
      for (let item of res) {
        dyVideoStateMap.value.set(item.VideoId, {
          ErrNo: item.ErrNo,
          ErrMsg: item.ErrMsg,
          Title: item.Title
        })
      }
    })
}


/**
 * -----------
 * 卡券配置
 * -----------
 */

/**
 * 
 */
let modalViewRef = ref();

/**
 * 展示
 */
let isModalViewRefShow = ref(false);

/**
 * 打开
 */
function openModalView(row: DyVideoDataClass) {
  isModalViewRefShow.value = true;
  nextTick(() => {
    modalViewRef.value.show(row.video_id, selectCmp.value?.Id);
  })
}

/**
 * 卡券配置成功
 */
function onEcardSubmit(para: {
  videoId: string
  title: string
}) {
  dyVideoStateMap.value.set(para.videoId, {
    ErrNo: 0,
    ErrMsg: "",
    Title: para.title
  })
}
/**
 * ====================
 *  页面初始化
 * ====================
 */

onMounted(() => {
  getCmpList();
})
</script>

<style lang="less" scoped>
.page-body {
  height: 100%;
  width: 100%;
  display: flex;
}

.page-left {
  flex-shrink: 0;
  flex-basis: 400px;
  border-right: 1px solid rgba(0, 0, 0, 0.1);
}

.page-left-item {
  cursor: pointer;
}

.page-left-item-select {
  outline: 2px solid var(--primaryColor);
  border-radius: 5px;
}

.page-right {
  height: 100%;
  flex-grow: 1;
  padding: 10px;
}

.page-right-none {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.3);
}

.page-right-con {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  padding: 1px;
  height: calc(100% - 60px);
  overflow: auto;

}

.page-right-con-item {
  margin: 5px;
  border-radius: 5px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  transition: 0.3s;
  display: flex;
  padding: 5px;
  height: 200px;

  &:hover {
    box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.05);
  }

  &>img {
    display: block;
    height: 100%;
    flex-shrink: 0;
    margin-right: 10px;
    border-radius: 5px;
  }
}

.page-right-page {
  flex-grow: 1;
  flex-basis: 100%;
  padding: 20px 0;
  display: flex;
  justify-content: center;
}

.page-right-con-itemcon {
  height: 100%;
  display: flex;
  flex-direction: column;

}

.page-right-con-itemcon-footer {
  flex-shrink: 0;
  height: 32px;
  display: flex;
  align-items: center;
}
</style>